<template>
  <div class="add-advertise-box">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="广告名称:" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>
      <el-form-item label="广告位置" prop="type">
        <el-select v-model="ruleForm.type" placeholder="请选择">
          <el-option label="PC首页轮播" :value="0" />
          <el-option label="APP首页轮播" :value="1" />
        </el-select>
      </el-form-item>

      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="ruleForm.startTime"
          type="date"
          placeholder="选择日期"
        />
      </el-form-item>

      <el-form-item label="到期时间" prop="endTime">
        <el-date-picker
          v-model="ruleForm.endTime"
          type="date"
          placeholder="选择日期"
        />
      </el-form-item>

      <el-form-item label="上线/下线:" prop="status">
        <el-radio-group v-model="ruleForm.status">
          <el-radio :label="0">线下</el-radio>
          <el-radio :label="1">线上</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="广告图片:" prop="pic">
        <el-upload
          v-model:file-list="fileList"
          class="upload-demo"
          action="http://xue.cnkdl.cn:9082/mall-admin/minio/upload"
          :on-preview="handlePreview"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          list-type="picture"
        >
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过100kb</div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="排序:" prop="sort">
        <el-input v-model="ruleForm.sort" />
      </el-form-item>

      <el-form-item label="广告链接:" prop="url">
        <el-input v-model="ruleForm.url" />
      </el-form-item>

      <el-form-item label="广告备注:" prop="note">
        <el-input
          v-model="ruleForm.note"
          type="textarea"
          rows="6"
          placeholder="请输入内容"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          提交
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from "vue";
import {
  ElMessage,
  ElMessageBox,
  FormInstance,
  FormRules,
  UploadProps,
  UploadUserFile,
} from "element-plus";
import {
  homeAdvertiseAddApi,
  homeAdvertiseCreateApi,
  homeAdvertiseUpdateApi,
} from "./api/index";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();

const ruleFormRef = ref<FormInstance>();
let ruleForm = reactive<any>({
  name: "", // 广告名称
  type: 1, // 广告位置
  startTime: "", // 开始时间
  endTime: "", // 结束时间
  status: 0, // 上线/下线
  pic: "", // 广告图片
  sort: 0, // 排序
  url: "", // 广告链接
  note: "", // 广告备注
});

const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入广告名称", trigger: "blur" }],
  type: [
    {
      required: false,
      trigger: "blur",
    },
  ],
  startTime: [
    {
      type: "date",
      required: true,
      message: "请选择开始时间",
      trigger: "blur",
    },
  ],
  endTime: [
    {
      type: "date",
      required: true,
      message: "请选择到期时间",
      trigger: "blur",
    },
  ],
  status: [
    {
      required: false,
      trigger: "blur",
    },
  ],
  pic: [
    {
      required: false,
      trigger: "blur",
    },
  ],
  sort: [
    {
      required: false,
      trigger: "blur",
    },
  ],
  url: [{ required: true, message: "请输入广告链接", trigger: "blur" }],
  note: [{ required: false, trigger: "blur" }],
});

const fileList = ref<UploadUserFile[]>([]);

watch(
  () => route.query.id,
  () => {
    if (route.query.id) {
      homeAdvertiseAddApi(route.query.id).then((res) => {
        if (res.code === 200) {
          Object.assign(ruleForm, res.data);
          ruleForm.type = ruleForm.type ? 1 : 0;
          fileList.value[0] = {
            name: res.data.pic,
            url: res.data.pic,
          };
        }
      });
    }
  },
  {
    immediate: true,
  }
);

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("是否提交数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (route.query.id) {
            homeAdvertiseUpdateApi(ruleForm).then((res) => {
              if (res.code === 200) {
                router.push("/sms/homeAdvertise");
                ElMessage.success("修改成功");
              }
            });
          } else {
            homeAdvertiseCreateApi(ruleForm).then((res) => {
              if (res.code === 200) {
                router.push("/sms/homeAdvertise");
                ElMessage.success("添加成功");
              }
            });
          }
        })
        .catch(() => {});
    } else {
      console.log("error submit!", fields, valid);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {};
const handleSuccess: UploadProps["onSuccess"] = (response) => {
  ruleForm.pic = response.data.url;
  ruleForm.name = response.data.name;
};
const handlePreview: UploadProps["onPreview"] = (file) => {};
</script>

<style scoped>
.add-advertise-box {
  width: 720px;
  padding: 35px 35px 15px;
  margin: 20px auto;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}
</style>
